using LikhodedDynamics.Sber.GigaChatSDK;
using LikhodedDynamics.Sber.GigaChatSDK.Models;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

namespace SAWD.AI
{

    public class AISender : MonoBehaviour
    {
        [TextArea(30, 10)]
        public string prompt = "";
        public string chatCreds = "";
        public static GigaChat Chat;
        public TMP_InputField text;
        public AIJSONBuilder awp;

        public void Start()
        {
            Chat = new GigaChat(chatCreds, false, true, true);
            awp = FindObjectOfType<AIJSONBuilder>();
        }

        public void clickButton()
        {
            submitText(text.text);
        }

        async public void submitText(string text)
        {
            await Chat.CreateTokenAsync();

            var contents = new List<MessageContent>();

            string hack = "```json{\"methods_calls\":[{";

            string buildedPrompt = prompt.Replace("{{#STATE#}}", awp.GetJSONState());
            Debug.Log(buildedPrompt);

            contents.Add(new MessageContent("system", buildedPrompt));
            contents.Add(new MessageContent("user", text));
            contents.Add(new MessageContent("assistant", hack));

            var mq = new MessageQuery(contents, "GigaChat-Pro", 1f, 0.87f, 1, false, 1024);
            //var mq = new MessageQuery(contents, "GigaChat:latest", 1f, 0.87f);

            var res = await Chat.CompletionsAsync(mq);

            string json = hack + res.choices[res.choices.Count - 1].message.content;
            string[] splitted = json.Split("```json");
            json = splitted.Length > 1 ? splitted[1] : splitted[0];
            splitted = json.Split("```");
            json = splitted[0];

            Debug.Log(json);

            awp.CallMethod(json);
        }

        [AI("Для разговора с игроком")]
        public void response([AI("Этот текст увидит игрок")] string text)
        {
            Debug.Log(text);
        }

    }

}